package com.example.recordingpen_datacollection.config.Interceptor;

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;  
import javax.servlet.http.HttpServletRequest;  
import javax.servlet.http.HttpServletResponse;  
import java.time.Duration;  
import java.time.Instant;  
import java.util.Deque;
import java.util.LinkedList;

//@Component
public class RateLimitInterceptorV1 implements HandlerInterceptor {
  
    private static final int MAX_REQUESTS = 10; // 最大存储的请求数量
    private static final long MINUTE_IN_MILLIS = 60 * 1000; // 1分钟毫秒数  
    private final Deque<Instant> requestTimestamps = new LinkedList<>();

    @Override  
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {  
        Instant now = Instant.now();

        // 添加请求时间戳到队列中  
        synchronized (requestTimestamps) {

            if(requestTimestamps.size()<MAX_REQUESTS){
                requestTimestamps.addLast(now);
                return true;
            }


            // 检查时间差
            System.out.println("ss :"+Duration.between(requestTimestamps.getFirst(), now).toMillis() );
            if (!requestTimestamps.isEmpty() &&
                Duration.between(requestTimestamps.getFirst(), now).toMillis() < MINUTE_IN_MILLIS) {
                // 时间差小于1分钟，拒绝访问
                response.setStatus(HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE);
                response.getWriter().write("Too many requests within 1 minute, access denied.");
                return false; // 返回false表示请求被拦截
            }
        }
        if (requestTimestamps.size() == MAX_REQUESTS) {
            requestTimestamps.removeFirst(); // 移除最旧的请求时间戳
        }
        requestTimestamps.addLast(now); // 添加新的请求时间戳
  
        // 允许请求继续处理  
        return true;  
    }  
}